<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>FileReader 图片视频上传 预览格式为Blob </title>
    <style type="text/css">
        .imgshow {
            padding: 2px;
            border: 2px antiquewhite;
            transition: background 1s;
            -moz-transition: background 1s;
            -webkit-transition: background 1s;
            -o-transition: background 1s;
        }
        .imgshow:hover {
            background: rgba(0, 0, 0, 0.2);
        }
        input[type=file] {
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            overflow: hidden;
            /* cursor: pointer; */
            /*设置input不显示*/
            /* opacity: 0; */
            background: url(../img/24.png) round;
            cursor: pointer;
            /* 上面的代码是常规设置， 即：引入一个图片背景，设置在中心位置，大小和按钮的大小一致，以及鼠标指针为手型 */
            /*设置背景图片大小*/
            background-size: 100%;
            display: block;
            font-size: 0;
            line-height: 0;
            text-indent: -9999px;
        }
        input[type=file]:active {
            border: white;
        }

        .imgcontshow{
            visibility:hidden;
            opacity:0;
            transform:scaleY(0);
            transition:.3s;
            animation:show .5s forwards;
        }
        @keyframes show{
            0% {
                visibility:visible;
                opacity: 1;
                transform: scaleY(0)
            }
            40% {
                visibility:visible;
                opacity: 1;
                transform: scaleY(1)
            }
            60% {
                visibility:visible;
                opacity: 1;
                transform: scaleY(0)
            }
            80% {
                visibility:visible;
                opacity: 1;
                transform: scaleY(2)
            }
            100% {
                visibility:visible;
                opacity: 1;
                transform: scaleY(1)
            }
        }

        @keyframes fadenum {
            /*设置内容由显示变为隐藏*/
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
</head>
<body>
<input type="file" multiple="multiple"  maxsize="50000" onchange="update()"  accept="image/gif,image/jpeg,image/png,image/jpg,video/mp4" />
<div id="imgsArry"></div>
<canvas></canvas>
</body>
<script type="text/javascript">
	
	class request {
		constructor(parameter) {
			// super();
			/*Content-type (几种常见的Content-Type类型)
			application/x-www-form-urlencoded
			multipart/form-data
			application/json
			text/xml
			application/json;charset=UTF-8
			*/
			const {
				url = null, data = {}, header = 'application/json;charset=UTF-8', way = 'post', datatype = 'JSON'
			} = parameter;
			return new Promise((resolve, reject) => {
				let xhr =  new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
				xhr.open(way, url, true);
				xhr.datatype = datatype;
				xhr.setRequestHeader('Content-type', `${header}`);
				xhr.timeout = 30000;
				if (xhr && xhr.timeout) {
					xhr.ontimeout = function () { /*请求超时触发的事件*/
						alert('请求超时!')
					};
				};
				xhr.send(JSON.stringify(data));
				xhr.onerror = function (e) { /*失败*/
					reject(new Error({
						errorType: 'abort_error',
						xhr: xhr
					}));
				};
				xhr.onreadystatechange = function () {
					if (xhr.readyState === 4 && xhr.status === 200) {
						resolve(JSON.parse(xhr.responseText));
					} else if (xhr.readyState >= 400 && xhr.status < 500) {
						reject(`错误请求，如语法错误http=>状态码:${xhr.readyState}`);
					} else if (xhr.status > 500) {
						reject(`服务器产生内部错误http=>状态码:${xhr.readyState}`);
					}
				}
			})
		}
	};
	
	// !function test(){
	//     // 捕获异常，递归次数过多调试工具会抛出异常。
	//     try { !
	//         function cir(i) {
	//             // 当打开调试工具后，抛出异常，setTimeout执行test无参数，此时i == NaN，("" + i / i).length == 3
	//             // debugger设置断点
	//             (1 !== ("" + i / i).length || 0 === i) &&
	//             function() {}.constructor("debugger")(),
	//             cir(++i);
	//         } (0)
	//     } catch(e) {
	//         setTimeout(test, 500)
	//     }
	// }()
	
	
    const imgs = document.querySelector('input[type=file]'); //获取file
    const imgsArry = document.getElementById('imgsArry');
    const filetype = imgs.getAttribute('datatype'); //获取自定义读取图片类型

    let imgsBlobArry = []; //存放blob数据
    let imgArrylist = []; //存放图片对象

    function update() {

        const typeFile = imgs.accept || imgs.accept.replace(/\s/g, "").split(",");
        if (parseInt(imgs.getAttribute("maxsize")) < imgs.files.length) {
            console.log("超出了数量");
            console.error('Exceeded number of custom files')
            // return false;
            back;
        }

        for (let i = 0; i < imgs.files.length; i++) { //获取的图片放入数组
            imgArrylist.push(imgs.files[i]);

         if (typeFile.indexOf(imgs.files[i].type) ===-1) { console.warn('上传文件类型有误'); continue; }

            let reader = new FileReader();

            reader.readAsDataURL(imgs.files[i]);

            reader.onerror = function(e) { //出错
                // console.log(e)
            };

            reader.onloadstart = function(e) { //开始读取
                // console.warn(e)
            };

            reader.onprogress = function (e) {
                parseInt(e.loaded/imgs.files[i].size*100)
            };

            reader.onload = function (e) {
                imgsBlobArry.push({
                    name:imgs.files[i].name,
                    fileType:imgs.files[i].type,
                    size:conver(imgs.files[i].size),
                    url:e.target.result,
                    lastModifiedDate:imgs.files[i].lastModifiedDate
                });

                let TheLabel;
                if (String(imgs.files[i].type).includes('image')) {
                    TheLabel = new Image;

                } else if (String(imgs.files[i].type).includes('video')) {
                    TheLabel = document.createElement('video');

                } else if (String(imgs.files[i].type).includes('audio')) {
                    TheLabel = new Audio;

                } else { //其他文件
                    TheLabel = document.createElement('div').innerHTML =`<img src="../img/file.jpg" alt="文件" style="width: 10%;">`
                }

                let imgCont = document.createElement('div'); //最外层div
                let close =  document.createElement('p'); //最外层div
                let progress = document.createElement('div'); // 显示进度条div
                close.className = 'close';
                close.style = `text-align: end;line-height: 0;cursor: pointer;`;
                close.innerHTML = `X`;

                TheLabel.style = `width:100%;height:100%`;
                TheLabel.src = e.target.result;
                TheLabel.id = "examine";
                imgCont.className = "imgshow imgcontshow";
                imgCont.style = `width: 10%;height: 10%;float: left;`;
                progress.style = `width:100%;height:0.2rem;background:#10affb`;
                imgCont.appendChild(close);
                imgCont.appendChild(TheLabel);
                imgCont.appendChild(progress);
                imgsArry.appendChild(imgCont);
				
				// console.log(dataURLtoBlob(e.target.result))
				// console.log(window.URL.(e.target.result))
				// console.log(e.target)
				
				
					console.log(imgsBlobArry)
				// postJSON('http://localhost:1088/imges',{city:e.target.result}).then()

				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
            }

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		// console.log(arr);
		// console.log(mime);
		// console.log(bstr);
		// console.log(n);
		// console.log(u8arr);
		
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
	console.log([u8arr])
    return new Blob([u8arr], { type: mime });
}

            // let   blobs = window.URL.createObjectURL(imgs.files[i]) //获取blob二进制数据，可用来显示

            // imgsBlobArry.push({
            //     name:imgs.files[i].name,
            //     fileType:imgs.files[i].type,
            //     size:conver(imgs.files[i].size),
            //     uer:blobs,
            //     lastModifiedDate:imgs.files[i].lastModifiedDate
            // });


        }
        // window.URL.revokeObjectURL(blobs) //手动回收
        setTimeout(()=>{
        if ( imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
            console.log("超出数量");
            imgs.style.display = 'none';
        } else {
            imgs.style.display = "table";
        }
        },50);

        function conver(limit) { //图片大小 mb 换算
            let size = "";
            if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
                size = limit.toFixed(2) + "B";
            } else if (limit < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB
                size = (limit / 1024).toFixed(2) + "KB";
            } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
                size = (limit / (1024 * 1024)).toFixed(2) + "MB";
            } else { //其他转化成GB
                size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
            }
            let sizestr = size + "";
            let len = sizestr.indexOf("\.");
            let dec = sizestr.substr(len + 1, 2);
            if (dec === "00") { //当小数点后为00时 去掉小数部分
                return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
            }
            return sizestr;
        }
    }


    //点击图片查看
    var el = window.document.body; //声明一个变量，默认值为body
    window.document.body.onclick = function(event) {
        if (event.target.id === "") {
            if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
                document.body.removeChild(document.getElementById('showimg'))
            }
        }
        let lookOver = document.getElementById('imgShow');
        if (event.target.tagName === 'IMG' || event.target.tagName === 'VIDEO' || event.target.tagName === 'Audio') {

            let showimg = event.target.tagName === "IMG" ? new Image : event.target.tagName === "VIDEO" ? document.createElement(
                'video'): new Audio;
            showimg.autoplay = true
            showimg.controls = true
            let divshow = document.createElement('div');
            showimg.style = `position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);animation: fadenum 2s forwards`;
            showimg.src = event.target.src;
            divshow.id = 'showimg';
            divshow.style = `position: fixed;top: 0px;width: 100%;height: 100%;background: rgba(0,0,0,0.1);text-align:center;`

            divshow.appendChild(showimg)

            if (!lookOver) {
                document.body.appendChild(divshow)
            }

        }

        if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
            document.body.removeChild(document.getElementById('showimg'))
        }


        if (event.target.tagName === 'P') {
            document.querySelectorAll('.close').forEach((tiem,index) => {
                tiem.onclick = function (){
                    console.log(this.parentNode);
                    document.getElementById('imgsArry').removeChild(this.parentNode);
                    imgsBlobArry.splice(index,1);

                    console.log(imgsBlobArry)
                }
            });
            if ( imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
                console.log("超出数量")
                imgs.style.display = 'none';

            } else {
                imgs.style.display = "table";
            }
        }
    };


function postJSON(url, data) {
    return new Promise( (resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open("POST", url, true)
		xhr.datatype = 'json'
        xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(JSON.parse(this.responseText), this)
                } else {
                    var resJson = { code: this.status, response: this.response }
                    reject(resJson, this)
                }
            }
        }

        xhr.send(JSON.stringify(data))
    })
}



// postJSON('http://60.10.165.110:8001/fbjd/msg/weather',{city:101090608}).then(data=>{console.log(data)})

</script>
</html>
